package com.example.helloserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class HelloController {

    @Autowired
    private DiscoveryClient client;
    @Autowired
    private Registration registration;

    @GetMapping("/hello")
    public String index(){
        ServiceInstance instance = getInstance();
        log.info("/hello,host: " + instance.getHost() + ", server_id: " + instance.getServiceId());
        return "Hello World";
    }

    private ServiceInstance getInstance(){
        List<ServiceInstance> instances = client.getInstances(registration.getServiceId());
        if(null != instances && instances.size() > 0){
            for(ServiceInstance item:instances){
                if(item.getServiceId().equals("HELLO-SERVICE"))
                    return item;
            }
        }

        return null;
    }

}
